package com.itheima.appserver.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.model.mongo.Visitors;
import com.itheima.dubbo.interfaces.VisitorsApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 来访者服务
 */
@Service
public class VisitorsService {

    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 查询来访者列表数据
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public List<Visitors> queryVisitorByPages(Long userId, Integer page, Integer pageSize) {
        return visitorsApi.queryVisitorByPages(userId, page, pageSize);
    }


    /**
     * 查询首页来访者头像
     *
     * @param userId
     * @param lastQueryDate
     * @return
     */
    public List<Visitors> queryTopVisitor(Long userId, Long lastQueryDate) {
        List<Visitors> visitors = visitorsApi.queryTopVisitor(userId, lastQueryDate);
        if (ObjectUtil.isEmpty(visitors)) {
            return Collections.EMPTY_LIST;
        }
        return visitors;
    }

    /**
     * 记录来访者信息
     *
     * @param visitorId 被访问者的ID
     */
    public void saveVisitor(Long visitorId) {
        Visitors visitors = new Visitors();
        visitors.setId(new ObjectId());
        visitors.setUserId(visitorId);
        visitors.setVisitorUserId(UserThreadLocal.getUserId());
        visitors.setFrom("个人主页");
        visitors.setDate(System.currentTimeMillis());
        visitorsApi.saveVisitor(visitors);
    }
}
